<template>
    <el-scrollbar height="100%">
        <div>
            <el-input v-model="filterText" :suffix-icon="Search" :placeholder="$t('请输入')">
                <template #append>
                    <el-dropdown>
                        <span>
                            <el-icon><MoreFilled /></el-icon>
                        </span>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item @click="expandAll">{{ $t('展开') }}</el-dropdown-item>
                                <el-dropdown-item @click="collapseAll">{{ $t('收缩') }}</el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </template>
            </el-input>
            <el-divider style="margin: 5px" />
            <!-- prettier-ignore -->
            <el-tree 
            ref="treeRef" 
            :data="deptdata" 
            node-key="deptid"
            v-loading="deptStore.loadding" 
            style="max-width: 300px; height: 100%" 
            :props="defaultProps" 
            default-expand-all 
            :filter-node-method="filterNode" 
            :expand-on-click-node="false" 
            @node-click="handleNodeClick"
            highlight-current
            >
                <template #default="{ node, data }">
                    <span class="custom-tree-node"  @dblclick="bdselect(data)">
                    <div v-if="node.isCurrent">
                    <span style="color:blue">{{ node.label }}</span>
                        <span v-if="!isreadonly">
                            <el-button link @click="append(data)" style="color: green; weight: 500; font-size: 20px"> + </el-button>
                            <el-button v-if="isformmodel" link @click="edit(data)" style="color: blue; weight: 500">
                                <el-icon><Edit /></el-icon>
                            </el-button>
                            <el-popconfirm :title="t('确定要删除吗?')" :confirm-button-text="$t('是')" :cancel-button-text="$t('否')" @confirm="deletedept" @cancel="canceldel">
                                <template #reference>
                                    <el-button link>
                                        <span style="font-size: 15px; color: red">
                                            <el-icon><Delete /></el-icon>
                                        </span>
                                    </el-button>
                                </template>
                            </el-popconfirm>
                        </span>
                    </div>
                    <div  v-else>
                        <span>{{ node.label }}</span>
                    </div>
                    </span>
                </template>
            </el-tree>
        </div>
    </el-scrollbar>
    <!-- 弹窗组件 -->
    <el-dialog v-model="dialogVisible" :title="formtitle" width="550">
        <el-form :model="formdata" label-width="130" style="max-width: 600px">
            <el-form-item :label="$t('部门编号')">
                <el-input v-model="formdata.deptid" />
            </el-form-item>
            <el-form-item :label="$t('部门名称')">
                <el-input v-model="formdata.deptnm" />
            </el-form-item>
            <el-form-item :label="$t('部门负责人')">
                <el-input v-model="formdata.leader" />
            </el-form-item>
            <el-form-item :label="$t('是否生产部门')">
                <el-switch v-model="formdata.isproddept" :active-value="1" :inactive-value="0" />
            </el-form-item>
            <el-form-item :label="$t('备注')">
                <el-input v-model="formdata.des" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogVisible = false">{{ $t('取消') }}</el-button>
                <el-button type="primary" @click="onSubmit(formdata)"> {{ $t('确定') }} </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { httpSend } from '../../utils/api';
import { onMounted, ref, reactive, watch,getCurrentInstance } from 'vue';
import { useI18n } from 'vue-i18n';
import { Search } from '@element-plus/icons-vue';
import { ElTree } from 'element-plus';
//@ts-ignore
import { usedeptStore } from '@/store';
import { chkgrant } from '@/globalmethods'; /*通用方法*/
const { t } = useI18n(); //多语言
const deptStore = usedeptStore() as any;
//树节点设置
const filterText = ref('');
const treeRef = ref<InstanceType<typeof ElTree>>();
const defaultProps = {
    children: 'children',
    label: 'deptnm',
};

const formtitle = ref('新增');
const dialogVisible = ref(false);

//接收父组件传递的 modelValue 属性
interface FormDatabaseProps {
    isformmodel?: any;
    isreadonly?: any;
}
const formdatabase = withDefaults(defineProps<FormDatabaseProps>(), {
    isformmodel: false,
    isreadonly: false,
});

const isformmodel = formdatabase.isformmodel ? true : false;
const isreadonly = formdatabase.isreadonly ? true : false;

//输入栏过滤
watch(filterText, (val) => {
    treeRef.value!.filter(val);
});
watch(
    () => deptStore.deptid,
    (newData) => {
        if (!newData) {
            treeRef.value?.setCurrentKey(null);
        }
    }
);
//输入栏过滤
const filterNode = (value: string, data: any) => {
    if (!value) return true;
    return data.deptnm.includes(value);
};
// 弹窗数据
let formdata: any = reactive({});
//总数据
let deptdata = reactive([]);
//总数
const allcount = ref(0);
//加载状态
const deptloading = ref(false);
const isuigrant = ref(false);
const { appContext } = getCurrentInstance();
const ElMessage = appContext.config.globalProperties.$ElMessage;
//初始化
onMounted(() => {
    isuigrant.value=chkgrant('部门档案', 'customset');
    if (deptStore.deptlist) {
        deptStore.setloadding(true);
        getNodes(deptStore.deptlist);
        deptdata = [...deptdata];
        deptStore.setloadding(false);
    } else {
        Getdeptdata();
    }
});

/**取部门根节点 */
const getNodes = (data) => {
    deptdata = [];
    data.forEach((v) => {
        if (!!!v.parentid) {
            deptdata.push({ ...v, children: getTree(v.treeid, data) });
        }
    });
};

/**获取部门子节点*/
const getTree = (parentid, data) => {
    let item = [];
    data.forEach((v) => {
        if (v.parentid == parentid) {
            item.push({ ...v, children: getTree(v.treeid, data) });
        }
    });
    return item;
};
//获取数据
const Getdeptdata = async () => {
    if (!chkgrant('部门档案', 'getdeptlist')) {
        ElMessage.warning(t('您暂无查看权限,请联系管理员!'));
        return;
    }
    deptStore.setloadding(true);
    const res = await httpSend('getdeptlist', {});
    if (res.data) {
        deptStore.setdeptlist(res.data);
        allcount.value = res.count;
        getNodes(res.data);
        deptStore.setloadding(false);
    }
};

//打开新增form
const append = (data: any) => {
    if (!chkgrant('部门档案', 'savedept')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    formtitle.value = t('新增');
    setTimeout(() => {
        for (let key in formdata) {
            if (formdata.hasOwnProperty(key)) {
                formdata[key] = null;
            }
        }
        formdata.parentid = data.treeid;
        dialogVisible.value = true;
    }, 10);
};
//打开编辑form
const edit = (data: any) => {
    if (!chkgrant('部门档案', 'savedept')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    formtitle.value = t('修改');
    dialogVisible.value = true;
};
//删除
const deletedept = async () => {
    if (!chkgrant('部门档案', 'deletedept')) {
        ElMessage.warning(t('您暂无删除权限,请联系管理员!'));
        return;
    }
    deptloading.value = true;
    deptStore.setloadding(true);
    try {
        const fd = new FormData();
        fd.append('param', JSON.stringify(formdata));
        const res = await httpSend('deletedept', fd);
        if (res.code === 1) {
            getNodes(res.data);
            deptdata = [...deptdata];
            deptStore.setdeptlist(res.data);
            deptStore.setdeptform(null);
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        deptloading.value = false;
        deptStore.setloadding(false);
    }
};
//取消删除
const canceldel = () => {
    console.log('cancel delete!');
};
//点击当前节点
const handleNodeClick = (data, node) => {
    formdata.id = data.id;
    formdata.deptid = data.deptid;
    formdata.deptnm = data.deptnm;
    formdata.isproddept = data.isproddept;
    formdata.des = data.des;
    formdata.leader = data.leader;
    deptStore.setdeptform(data);
    deptStore.setdeptid(data.deptid);
    deptStore.setdeptnm(data.deptnm);
    //emit('haveselect', {list:data,select:'singleclick'});
};
//保存
const onSubmit = async (subdata) => {
    if (!chkgrant('部门档案', 'savedept')) {
        ElMessage.warning(t('您暂无保存权限,请联系管理员!'));
        return;
    }
    const fd = new FormData();
    fd.append('param', JSON.stringify(subdata));
    deptStore.setloadding(true);
    try {
        const res = await httpSend('savedept', fd);
        if (res.code === 1) {
            dialogVisible.value = false;
            getNodes(res.data);
            deptdata = [...deptdata];
            deptStore.setdeptlist(res.data);
            deptStore.setdeptform(res.nowdata);
        } else {
            console.log('失败');
        }
    } catch (error) {
        console.error('请求失败', error);
    } finally {
        deptStore.setloadding(false);
    }
};

// 使用 defineExpose 暴露方法
defineExpose({
    onSubmit,
    canceldel,
});
// 一键展开
const expandAll = async () => {
    Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.expand());
};

// 一键收缩
const collapseAll = () => {
    Object.values(treeRef.value.store.nodesMap).forEach((v: any) => v.collapse());
};

const bdselect = (data) => {
    deptStore.setselect(true);
};
</script>
<style scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
